﻿namespace Nello.Web.Controls
{
    using System;
    using System.ComponentModel;
    using System.Resources;
    using System.Runtime.CompilerServices;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    [DefaultProperty("Text"), Designer("System.Web.UI.Design.ControlDesigner"), ToolboxData("<{0}:ContextMenu runat=server></{0}:ContextMenu>"), DefaultEvent("MenuClick"), ControlBuilder(typeof(PlaceHolderControlBuilder))]
    public class ContextMenu : TextBox
    {
        private string menus = "";

        public event ClickEventHandle MenuClick;

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.AutoPostBack = true;
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            if (this.MenuClick != null)
            {
                this.MenuClick(this.Text);
            }
        }

        protected override void Render(HtmlTextWriter output)
        {
            string s = "";
            output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            output.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID);
            output.AddAttribute(HtmlTextWriterAttribute.Type, "hidden");
            output.AddAttribute(HtmlTextWriterAttribute.Value, this.Text);
            output.RenderBeginTag(HtmlTextWriterTag.Input);
            output.RenderEndTag();
            s = "\n<script language=javascript>\n";
            s = ((s + "function " + this.ClientID + "_MenuClick(menu)\n{\n") + "document.getElementById('" + this.ClientID + "').value=menu;\n") + this.Page.ClientScript.GetPostBackEventReference(this, null) + ";}\n</script>\n";
            output.Write(s);
            s = new ResourceManager(typeof(ContextMenu)).GetString("LibraryScript");
            output.Write(s);
        }

        public void SetMenus(string smenus)
        {
            this.menus = smenus.Replace(",", "\",\"");
            this.menus = "\"" + this.menus + "\"";
        }

        public void SetSource(WebControl ctl)
        {
            ctl.Attributes["oncontextmenu"] = "PopupMenu(new Array(" + this.menus + "),'" + this.ClientID + "');return false;";
        }

        public delegate void ClickEventHandle(string MenuText);
    }
}

